<template>
    <div class="app-container">
        <el-form :model="filterParams" label-width="auto">
            <div class="params-form params-form-gray">
                <el-form-item label="实名名称">
                    <el-input placeholder="请输入" v-model="filterParams.realName"></el-input>
                </el-form-item>
                <el-form-item label="财务单据编号">
                    <el-input placeholder="请输入" v-model="filterParams.slipCode"></el-input>
                </el-form-item>
                <el-form-item label="业务单据编号">
                    <el-input placeholder="请输入" v-model="filterParams.orderCode"></el-input>
                </el-form-item>
                <el-form-item label="单据类型">
                    <el-select placeholder="请选择" v-model="filterParams.slipType">
                        <el-option v-for="item, index in slipType" :label="item" :value="Number(index)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="核销状态">
                    <el-select placeholder="请选择" v-model="filterParams.cancelState">
                        <el-option v-for="item, index in verificationType" :label="item" :value="Number(index)" />
                    </el-select>
                </el-form-item>
                <el-form-item class="end-buttons">
                    <el-button :icon="Search" type="primary" @click="getOnlineDataList">
                        查询
                    </el-button>
                    <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </div>
        </el-form>
        <div class="table-operate">
            <el-button type="primary" :disabled="!tableCheckList.length" @click="openBatchPay">批量收付款</el-button>
            <el-button plain type="primary" :disabled="!tableCheckList.length" @click="setBilling(2)">设为已开票</el-button>
            <el-button plain type="primary" :disabled="!tableCheckList.length" @click="setBilling(1)">设为未开票</el-button>
        </div>
        <div class="table">
            <el-table :data="onlineList" style="width: 100%" max-height="calc(100vh - 400px)"
                @selection-change="selectionTable">
                <el-table-column type="selection" width="55" fixed="left" />
                <el-table-column prop="slipCode" label="编号" width="160" />
                <el-table-column prop="slipTypeName" label="单据类型" width="160"/>
                <el-table-column prop="receiptMemberName" label="收款方" width="300">
                    <template #default="scope">
                        <div class="desc">{{ splicing([scope.row.receiptMemberName, scope.row.receiptMemberId], '-') }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="payMemberName" label="付款方(最近1笔)" width="300">
                    <template #default="scope">
                        <div class="desc">{{ splicing([scope.row.payMemberName, scope.row.payMemberId], '-') }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="city" label="核销状态" width="120">
                    <template #default="scope">
                        {{ verificationType[scope.row.cancelState] }}
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="总金额" width="120">
                    <template #default="scope">
                        ￥{{ scope.row.plainMoney }}
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="已核销金额" width="180">
                    <template #default="scope">
                        ￥{{ scope.row.inMoney }}
                    </template>
                </el-table-column>
                <el-table-column prop="transferDate" label="本期金额" width="250">
                    <template #default="scope">
                        ￥{{ scope.row.currentPlainMoney }}
                    </template>
                </el-table-column>
                <el-table-column prop="transferDate" label="本期已核销" width="250">
                    <template #default="scope">
                        ￥{{ scope.row.currentPaidMoney || '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="transferDate" label="需开票" width="250">
                    <template #default="scope">
                        {{ whetherBilling[scope.row.isBill] }} <span>({{ billingStatus[scope.row.billState] }})</span>
                    </template>
                </el-table-column>
                <el-table-column prop="orderCode" label="关联单据" width="250" />
                <el-table-column prop="createTime" label="创建时间" width="250" />
                <el-table-column prop="createBy" label="创建人" width="250" />
                <el-table-column label="操作" fixed="right" width="120">
                    <template #default="scope">
                        <el-button type="primary" link size="small" @click="toPayment(scope.row)">查看流水</el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty />
                </template>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination v-model:current-page="pageQuery.current" v-model:page-size="pageQuery.size"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="getOnlineDataList" @current-change="getOnlineDataList" />
        </div>
        <el-dialog v-model="batchPayVisible" :show-close="false" width="400" center align-center
            class="batch-pay-dialog" @close="batchPayClose">
            <template #title>
                <custom-title title="付款" />
            </template>
            <div class="batch-pay-dialog_total">您选择了{{ tableCheckList.length }}个{{ slipType[batchPayParams.slipType] }}
            </div>
            <div class="batch-pay-dialog_money">
                <div>
                    <div class="batch-pay-dialog_money_num">￥{{ formattedAmount(batchPayParams.money) }}</div>
                    <div class="batch-pay-dialog_money_title">本期合计金额</div>
                </div>
                <div>
                    <div class="batch-pay-dialog_money_num">{{ batchPayParams.receiptMemberName }}</div>
                    <div class="batch-pay-dialog_money_title">付给</div>
                </div>
            </div>
            <el-form label-width="auto" :model="batchPayParams" :rules="payRules" ref="payFormRef">
                <el-form-item label="我的账户" prop="payMemberId">
                    <el-select placeholder="请选择" style="flex: 1;" v-model="batchPayParams.payMemberId"
                        @change="changePayMember">
                        <el-option v-for="item in myAccountList" :label="item.memberName"
                            :value="item.memberId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="付款方式" prop="payConfigId" v-if="batchPayParams.payMemberId">
                    <el-radio-group v-model="batchPayParams.payConfigId" @change="getBankCardList">
                        <el-radio :value="20" label="网银支付" v-if="showBanking"></el-radio>
                        <el-radio :value="21" label="快捷支付" v-if="showShortcut"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <template v-if="batchPayParams.payConfigId === 20">
                    <el-form-item label="银行" prop="bankCode">
                        <el-select-v2 v-model="batchPayParams.bankCode" filterable remote :remote-method="searchBank"
                            clearable :options="bankList" placeholder="请输入" style="flex: 1;" :props="prop" />
                    </el-form-item>
                    <el-form-item label="账户类型" prop="bankCardType">
                        <el-radio-group v-model="batchPayParams.bankCardType">
                            <el-radio label="储蓄卡" value="DEBIT_CARD"></el-radio>
                            <el-radio label="信用卡" value="CREDIT_CARD"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
                <template v-if="batchPayParams.payConfigId === 21">
                    <el-form-item label="银行卡号" prop="bankCardNo">
                        <el-select v-model="batchPayParams.bankCardNo" @change="setMobile">
                            <el-option v-for="item in bankCardList" :label="`${item.bankName} - ${item.cardNo}`"
                                :value="item.cardNo"></el-option>
                        </el-select>
                    </el-form-item>
                </template>
                <template v-if="batchPayParams.bankCardNo && batchPayParams.payConfigId === 21">
                    <el-form-item label="银行预留手机号">
                        <div class="readonly">{{ batchPayParams?.mobile }}</div>
                    </el-form-item>
                    <el-form-item label="验证码">
                        <div class="space">
                            <el-input placeholder="请输入" v-model="batchPayParams.verificationCode" />
                            <el-button type="primary" v-if="!sendCodeStatus.status"
                                @click="payLaunch">获取验证码</el-button>
                            <el-button v-else>重新获取({{ sendCodeStatus.time }}s)</el-button>
                        </div>
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="batchPayVisible = false">取消</el-button>
                    <el-button type="primary" @click="payLaunch" v-if='batchPayParams.payConfigId == 20'>
                        确定
                    </el-button>
                    <el-button type="primary" @click="payComfirm" v-else>
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { RefreshRight, Search } from '@element-plus/icons-vue';
import { getOnlineList, invoice, launchPay, comfirmPay } from "@/apis/online";
import { getWalletAccountList, getSupportBankList, getWithdrawAccountList } from "@/apis/purse";
import { slipType, verificationType, billingStatus, whetherBilling, tenantParams } from "@/utils/config";
import { formattedAmount, splicing } from "@/utils";
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router";

const payFormRef = ref()
const batchPayVisible = ref(false)
const router = useRouter();
const filterParams = ref({});
const onlineList = ref([]);
const total = ref(0);
const myAccountList = ref([])
const pageQuery = ref({
    current: 1,
    size: 10
})
const batchPayParams = ref()
const tableCheckList = ref([])
const reset = () => {
    filterParams.value = {};
    getOnlineDataList()
}
const payRules = {
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^[0-9]{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
    ],
    payMemberId: [
        { required: true, message: '请选择付款方', trigger: 'change' }
    ],
    payConfigId: [
        { required: true, message: '请选择付款方式', trigger: 'change' }
    ],
    bankCardType: [
        { required: true, message: '请选择账户类型', trigger: 'change' }
    ],
    bankCode: [
        { required: true, message: '请选择银行编码', trigger: 'change' }
    ],
    bankCardNo: [
        { required: true, message: '请选择银行卡号', trigger: 'change' }
    ]
}
const showBanking=computed(() => {
    const currentWallet = myAccountList.value.find(item => item.memberId === batchPayParams.value.payMemberId);
    if(!currentWallet)return false;
    return !['1'].includes(currentWallet.memberType);
});
const showShortcut = computed(() => {
    const currentWallet = myAccountList.value.find(item => item.memberId === batchPayParams.value.payMemberId);
    if(!currentWallet)return false;
    return !['2'].includes(currentWallet.memberType);
})
/**
 * 验证码当前状态
 */
const sendCodeStatus = ref({
    status: false,
    time: 60,
    timer: null
})
/**
 * 重置倒计时
 */
const clearTimer = () => {
    sendCodeStatus.value.status = false;
    clearInterval(sendCodeStatus.value.timer);
    sendCodeStatus.value.time = 60;
}
/**
 * 发送验证码之后的回调
 */
const sendCodeCallback = () => {
    sendCodeStatus.value.status = true;
    sendCodeStatus.value.timer = setInterval(() => {
        sendCodeStatus.value.time--;
        if (sendCodeStatus.value.time <= 0) {
            clearTimer()
        }
    }, 1000)
}
const setMobile = () => {
    const currentBankCard = bankCardList.value.find(v => v.cardNo === batchPayParams.value.bankCardNo);
    batchPayParams.value.mobile = currentBankCard.cardTel
}
const batchPayClose = () => {
    batchPayParams.value = {};
    payFormRef.value.resetFields()
}
/**
 * 模糊查询银行
 */
const searchBank = (key) => {
    keyword.value = key;
}
const prop = {
    value: 'bankCode',
    label: 'bankName'
}
const bankListData = ref([])
/**
 * 可用银行列表
 */
const bankList = computed(() => bankListData.value.filter(item => item.bankName.indexOf(keyword.value) !== -1))
const keyword = ref()

/**
 * 获取可用银行列表
 */
const getBankList = async () => {
    try {
        const res = await getSupportBankList()
        bankListData.value = res.data;
    } catch (error) {

    }
}
/**
 * 新开页面并跳转收支流水
 */
const toPayment = (item) => {
    const routeInfo = router.resolve({
        path: '/finance/payments',
        query: {
            slipCode: item.slipCode,
            slipType: item.slipType
        }
    });
    const url = routeInfo.href;
    window.open(url, '_blank')
}
/**
 * 获取表格数据
 */
const getOnlineDataList = async () => {
    try {
        const res = await getOnlineList(pageQuery.value, filterParams.value);
        onlineList.value = res.data.list || [];
        total.value = res.data.total || 0;
    } catch (error) {
        console.log(error)
    }
}
const bankCardList = ref([])
/**
 * 获取银行卡列表
 */
const getBankCardList = async () => {
    if (batchPayParams.value.payConfigId != 21) return;
    try {
        const currentAccount = myAccountList.value.find(v => v.memberId == batchPayParams.value.payMemberId)
        const res = await getWithdrawAccountList({ walletId: currentAccount.walletId, accountType: 'INDIVIDUAL' });
        bankCardList.value = res.data
    } catch (error) {
        console.log(error)
    }
}
/**
 * 改变会员账户 
 */
const changePayMember = async (value) => {
    batchPayParams.value.payConfigId = 20;
    batchPayParams.value.payMemberId = value;
    getBankCardList();
}
/**
 * 选择表格数据
 * @param {*} val 
 */
const selectionTable = (val) => {
    tableCheckList.value = val.map(v => v);
}
/**
 * 设置是否开票
 */
const setBilling = async (billStatus) => {
    const params = {
        slipIds: tableCheckList.value.map(v => v.slipId),
        billStatus
    }
    try {
        await invoice(params);
        getOnlineDataList();
        ElMessage.success('设置成功')
    } catch (error) {
        console.log(error)
    }
}

/**
 * 批量收付款
 */
const openBatchPay = () => {
    const isPayeeSame = tableCheckList.value.every(v => v.receiptMemberId == tableCheckList.value[0].receiptMemberId);
    if (!isPayeeSame) return ElMessage.error('请选择相同收款人单据');
    const isTypeSame = tableCheckList.value.every(v => v.slipType == tableCheckList.value[0].slipType);
    if (!isTypeSame) return ElMessage.error('请选择相同单据类型');
    const slipIds = tableCheckList.value.map(v => v.slipId);
    const money = tableCheckList.value.reduce((a, b) => a + Number(b.currentPlainMoney), 0).toFixed(2);
    batchPayParams.value = {
        ...batchPayParams.value,
        slipIds,
        source: 1,
        money,
        receiptMemberName: tableCheckList.value[0].receiptMemberName,
        slipType: tableCheckList.value[0].slipType,
        payConfigId: 20
    }
    const defaultAccountList = myAccountList.value.filter(v => v.isDefault);
    if (defaultAccountList.length) {
        batchPayParams.value.payMemberId = defaultAccountList[0].memberId;
        changePayMember(defaultAccountList[0].memberId);
    }
    batchPayVisible.value = true;
}
const payDetails = ref({})
/**
 * 发起支付
 */
const payLaunch = async () => {
    payFormRef.value.validate(async (valid) => {
        if (!valid) return;
        try {
            const res = await launchPay(batchPayParams.value);
            getOnlineDataList()
            if (res.data.paymentInfo) {
                window.open(res.data.paymentInfo);
                batchPayVisible.value = false;
                return;
            }
            sendCodeCallback()
            ElMessage.success('发送成功')
            payDetails.value = res.data;
        } catch (error) {
        }
    })
}
const payComfirm = async () => {
    try {
        await comfirmPay({ ...payDetails.value, verificationCode: batchPayParams.value.verificationCode });
        ElMessage.success('支付成功')
        batchPayVisible.value = false
        getOnlineDataList()
        batchPayVisible.value = false;
        clearTimer()
    } catch (error) {
        console.log(error)
    }
}
/**
 * 获取账户可用列表
 */
const getMyAccount = async () => {
    const res = await getWalletAccountList({ ...tenantParams, useStatus: 1 });
    myAccountList.value = res.data;
}
onMounted(() => {
    getOnlineDataList();
    getMyAccount();
    getBankList()
})
</script>

<style lang="scss" scoped>
.params-form {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 50px;

    >div:last-child {
        grid-column: 3;

        ::v-deep(.el-form-item__content) {
            display: flex;
            justify-content: end;
        }
    }
}

.table {
    border: $border;

    ::v-deep(.el-table tr) {
        height: 46px;

        .is-link {
            color: $topic;
        }

        td,
        th {
            border-bottom: $border;
        }

        .cell {
            display: flex;
            justify-content: center;
        }
    }

    ::v-deep(.el-table thead tr th.el-table__cell) {
        background: #F2F6FC !important;

        >th {
            background: transparent;
            text-align: center;
        }

        .el-table-fixed-column--right {
            background: #F2F6FC;
        }

    }

    ::v-deep(.el-table tbody tr:nth-child(even)) {
        background: #F2F6FC;
    }

    ::v-deep(.el-table tbody tr:last-child) {
        td {
            border-bottom: none !important;
        }

    }

    ::v-deep(.el-table__inner-wrapper) {
        &::before {
            display: none;
        }
    }
}

.space {
    display: flex;
    gap: 10px;
}

.qr-code {
    display: grid;
    grid-template-columns: 1fr;
    justify-items: center;
}
</style>
<style lang="scss">
.batch-pay-dialog {
    &_total {
        font-size: 12px;
        color: #86909C;
    }

    &_money {
        @include mixin.flex-between;
        gap: 4px;
        height: 84px;
        margin: 10px 0;

        >div {
            flex: 1;
            background: #EEF1F4;
            border-radius: 4px;
            display: grid;
            grid-template-columns: 1fr;
            text-align: center;
            padding: 20px;
            box-sizing: border-box;
        }

        &_num {
            font-size: 16px;
            color: #3D3D3D;
        }

        &_title {
            font-size: 12px;
            color: #86909C;
        }
    }
}
</style>